package com.umeox.auto_update

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.umeox.logger.UMLogger
import com.umeox.sdk_ring.RingScanCallback
import com.umeox.sdk_ring.UMScanResult
import com.umeox.sdk_ring.scan.RingScanner

object DeviceSearchManager {

    private const val TAG = "DeviceSearchManager"

    val processedDeviceList = arrayListOf<String>()
    val waitReconnectDeviceList = arrayListOf<String>()

    private var targetNumber = 0

    private val lock = Any()

    @SuppressLint("MissingPermission")
    private val call: RingScanCallback = object : RingScanCallback {
        override fun onScanResult(result: UMScanResult) {
            if (TextUtils.isEmpty(result.device.name)) {
                return
            }
            if (processedDeviceList.contains(result.device.address)) {
                return
            }
            if (waitReconnectDeviceList.contains(result.device.address)) {
                return
            }

            val targetName = AutoUpdateManager.getTargetDeviceName()
            val nameRegex = Regex(targetName)
            if (result.device.name.matches(nameRegex)) {
                synchronized(lock) {
                    if (targetNumber > 0) {
                        val device = AutoUpdateDevice()
                        device.name = result.device.name
                        device.mac = result.device.address
                        device.rssi = result.rssi
                        AutoUpdateManager.addDevice(device)
                        targetNumber--
                        UMLogger.d(TAG, "完成目标数 targetNumber = $targetNumber")
                        if (targetNumber <= 0) {
                            scannerManager.stopScan()
                        }
                    }
                }
            }
        }
    }

    private val scannerManager = RingScanner(this, call, Handler(Looper.getMainLooper()))


    fun requestDeviceJoin(reason: String) {
        synchronized(lock) {
            UMLogger.d(TAG, "开始请求设备加入---- reason:$reason")
            targetNumber++
            UMLogger.d(TAG, "新增目标数 targetNumber = $targetNumber")
            scannerManager.startScan()
        }

    }
}